﻿using System;
using System.Configuration;
using CSharpLogger.Common;

namespace CSharpLogger
{
    public class CSharpLoggerConfiguration
    {
        private static volatile CSharpLoggerConfiguration _configuration;

        private LogLevel _level;

        private static object _current = new object();

        public static CSharpLoggerConfiguration Configuration
        {
            get
            {
                lock (_current)
                {
                    if (_configuration == null)
                    {
                        _configuration = new CSharpLoggerConfiguration();
                    }

                    return _configuration;
                }
            }
        }

        private CSharpLoggerConfiguration()
        {
            _level = LogLevel.OFF;
        }

        public void SetLogLevel(LogLevel level)
        {
            _level = level;
        }

        public LogLevel GetLogLevel()
        {
            try
            {
                var logLevel = ConfigurationManager.AppSettings["LogLevel"].ToString();

                switch (logLevel.ToUpper())
                {
                    case "OFF":
                        return LogLevel.OFF;
                    case "INFO":
                        return LogLevel.INFO;
                    case "WARN":
                        return LogLevel.WARN;
                    case "ERROR":
                        return LogLevel.ERROR;
                    case "FATAL":
                        return LogLevel.FATAL;
                    case "DEBUG":
                        return LogLevel.DEBUG;
                    default:
                        return _level;
                }
            }
            catch (NullReferenceException)
            {
                return _level;
            }
            catch (Exception)
            {
                return _level;
            }
        }
    }
}
